package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.PostEntity;
import com.example.HaiDLaobackend.entity.PostFavoriteEntity;
import com.example.HaiDLaobackend.entity.PostLikeEntity;
import com.example.HaiDLaobackend.entity.UserEntity;
import com.example.HaiDLaobackend.service.PostFavoriteService;
import com.example.HaiDLaobackend.service.PostLikeService;
import com.example.HaiDLaobackend.service.PostService;
import com.example.HaiDLaobackend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/posts")
public class PostController {

	private final PostService postService;
	private final UserService userService;
	private final PostLikeService postLikeService;
	private final PostFavoriteService postFavoriteService;

	public PostController(PostService postService, UserService userService, 
			PostLikeService postLikeService, PostFavoriteService postFavoriteService) {
		this.postService = postService;
		this.userService = userService;
		this.postLikeService = postLikeService;
		this.postFavoriteService = postFavoriteService;
	}

	@PostMapping("/upload")
	public ApiResponse<String> uploadImage(
			@RequestParam("file") MultipartFile file,
			@RequestParam(value = "postId", required = false) Long postId) {
		if (file.isEmpty()) {
			return ApiResponse.error("文件为空");
		}
		
		try {
			// 获取项目根目录（pom文件所在目录）
			String projectRoot = System.getProperty("user.dir");
			File uploadDir;
			
			if (postId != null) {
				// 如果提供了postId，保存到对应的帖子目录
				uploadDir = new File(projectRoot, "uploads/posts/" + postId);
			} else {
				// 如果没有postId，先保存到临时目录
				uploadDir = new File(projectRoot, "uploads/posts/temp");
			}
			
			if (!uploadDir.exists()) {
				uploadDir.mkdirs();
			}
			
			// 生成唯一文件名
			String originalFilename = file.getOriginalFilename();
			String extension = originalFilename != null && originalFilename.contains(".") 
				? originalFilename.substring(originalFilename.lastIndexOf(".")) 
				: "";
			String filename = UUID.randomUUID().toString() + extension;
			File destFile = new File(uploadDir, filename);
			
			// 保存文件
			file.transferTo(destFile);
			
			// 返回相对路径
			if (postId != null) {
				return ApiResponse.ok("/uploads/posts/" + postId + "/" + filename);
			} else {
				return ApiResponse.ok("/uploads/posts/temp/" + filename);
			}
		} catch (IOException e) {
			return ApiResponse.error("文件上传失败: " + e.getMessage());
		}
	}

	@PostMapping
	public ApiResponse<PostEntity> createPost(
			@RequestBody PostEntity post,
			HttpServletRequest request) {
		
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		// 违禁词审核
		String title = post.getTitle() != null ? post.getTitle() : "";
		String content = post.getContent() != null ? post.getContent() : "";
		String checkText = title + " " + content;
		
		if (postService.containsForbiddenWords(checkText)) {
			return ApiResponse.error("内容包含违禁词，无法发布");
		}
		
		// 获取用户信息
		UserEntity user = userService.getById(userId);
		if (user == null) {
			return ApiResponse.error("用户不存在");
		}
		
		// 设置帖子信息
		post.setAuthorId(userId);
		post.setAuthorName(user.getNickname() != null ? user.getNickname() : user.getUsername());
		post.setCreatedAt(LocalDateTime.now());
		
		// 保存帖子
		postService.save(post);
		
		// 如果图片路径是临时目录，移动到对应的帖子目录
		if (post.getImageUrl() != null && post.getImageUrl().startsWith("/uploads/posts/temp/")) {
			try {
				String projectRoot = System.getProperty("user.dir");
				String tempPath = post.getImageUrl();
				String filename = tempPath.substring(tempPath.lastIndexOf("/") + 1);
				
				File tempFile = new File(projectRoot, tempPath);
				File postDir = new File(projectRoot, "uploads/posts/" + post.getId());
				if (!postDir.exists()) {
					postDir.mkdirs();
				}
				
				File newFile = new File(postDir, filename);
				if (tempFile.exists()) {
					tempFile.renameTo(newFile);
					post.setImageUrl("/uploads/posts/" + post.getId() + "/" + filename);
					postService.updateById(post);
				}
			} catch (Exception e) {
				// 移动失败不影响帖子创建，只记录日志
				System.err.println("移动帖子图片失败: " + e.getMessage());
			}
		}
		
		return ApiResponse.ok(post);
	}

	@GetMapping
	public ApiResponse<Page<PostEntity>> getPosts(
			@RequestParam(defaultValue = "1") long pageNum,
			@RequestParam(defaultValue = "20") long pageSize) {
		
		LambdaQueryWrapper<PostEntity> qw = new LambdaQueryWrapper<>();
		qw.orderByDesc(PostEntity::getCreatedAt);
		
		Page<PostEntity> page = postService.page(new Page<>(pageNum, pageSize), qw);
		return ApiResponse.ok(page);
	}

	@GetMapping("/{id}")
	public ApiResponse<Map<String, Object>> getPost(
			@PathVariable Long id,
			HttpServletRequest request) {
		PostEntity post = postService.getById(id);
		if (post == null) {
			return ApiResponse.error("帖子不存在");
		}
		
		Map<String, Object> result = new HashMap<>();
		result.put("post", post);
		
		// 获取点赞数和收藏数
		long likeCount = postLikeService.count(new LambdaQueryWrapper<PostLikeEntity>()
			.eq(PostLikeEntity::getPostId, id));
		long favoriteCount = postFavoriteService.count(new LambdaQueryWrapper<PostFavoriteEntity>()
			.eq(PostFavoriteEntity::getPostId, id));
		
		result.put("likeCount", likeCount);
		result.put("favoriteCount", favoriteCount);
		
		// 检查当前用户是否已点赞/收藏
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId != null) {
			boolean isLiked = postLikeService.count(new LambdaQueryWrapper<PostLikeEntity>()
				.eq(PostLikeEntity::getPostId, id)
				.eq(PostLikeEntity::getUserId, userId)) > 0;
			boolean isFavorited = postFavoriteService.count(new LambdaQueryWrapper<PostFavoriteEntity>()
				.eq(PostFavoriteEntity::getPostId, id)
				.eq(PostFavoriteEntity::getUserId, userId)) > 0;
			
			result.put("isLiked", isLiked);
			result.put("isFavorited", isFavorited);
		} else {
			result.put("isLiked", false);
			result.put("isFavorited", false);
		}
		
		return ApiResponse.ok(result);
	}
	
	@PostMapping("/{id}/like")
	public ApiResponse<Map<String, Object>> toggleLike(
			@PathVariable Long id,
			HttpServletRequest request) {
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		LambdaQueryWrapper<PostLikeEntity> qw = new LambdaQueryWrapper<>();
		qw.eq(PostLikeEntity::getPostId, id)
			.eq(PostLikeEntity::getUserId, userId);
		
		PostLikeEntity existing = postLikeService.getOne(qw);
		boolean isLiked;
		
		if (existing != null) {
			postLikeService.removeById(existing.getId());
			isLiked = false;
		} else {
			PostLikeEntity like = new PostLikeEntity();
			like.setPostId(id);
			like.setUserId(userId);
			like.setCreatedAt(LocalDateTime.now());
			postLikeService.save(like);
			isLiked = true;
		}
		
		long likeCount = postLikeService.count(new LambdaQueryWrapper<PostLikeEntity>()
			.eq(PostLikeEntity::getPostId, id));
		
		Map<String, Object> result = new HashMap<>();
		result.put("isLiked", isLiked);
		result.put("likeCount", likeCount);
		
		return ApiResponse.ok(result);
	}
	
	@PostMapping("/{id}/favorite")
	public ApiResponse<Map<String, Object>> toggleFavorite(
			@PathVariable Long id,
			HttpServletRequest request) {
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		LambdaQueryWrapper<PostFavoriteEntity> qw = new LambdaQueryWrapper<>();
		qw.eq(PostFavoriteEntity::getPostId, id)
			.eq(PostFavoriteEntity::getUserId, userId);
		
		PostFavoriteEntity existing = postFavoriteService.getOne(qw);
		boolean isFavorited;
		
		if (existing != null) {
			postFavoriteService.removeById(existing.getId());
			isFavorited = false;
		} else {
			PostFavoriteEntity favorite = new PostFavoriteEntity();
			favorite.setPostId(id);
			favorite.setUserId(userId);
			favorite.setCreatedAt(LocalDateTime.now());
			postFavoriteService.save(favorite);
			isFavorited = true;
		}
		
		long favoriteCount = postFavoriteService.count(new LambdaQueryWrapper<PostFavoriteEntity>()
			.eq(PostFavoriteEntity::getPostId, id));
		
		Map<String, Object> result = new HashMap<>();
		result.put("isFavorited", isFavorited);
		result.put("favoriteCount", favoriteCount);
		
		return ApiResponse.ok(result);
	}
	
	@GetMapping("/favorites")
	public ApiResponse<List<PostEntity>> getFavoritePosts(
			HttpServletRequest request) {
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		// 获取用户收藏的帖子ID列表
		List<PostFavoriteEntity> favorites = postFavoriteService.list(
			new LambdaQueryWrapper<PostFavoriteEntity>()
				.eq(PostFavoriteEntity::getUserId, userId)
				.orderByDesc(PostFavoriteEntity::getCreatedAt)
		);
		
		if (favorites.isEmpty()) {
			return ApiResponse.ok(new java.util.ArrayList<>());
		}
		
		// 获取帖子ID列表
		List<Long> postIds = favorites.stream()
			.map(PostFavoriteEntity::getPostId)
			.collect(java.util.stream.Collectors.toList());
		
		// 查询帖子详情
		List<PostEntity> posts = postService.list(
			new LambdaQueryWrapper<PostEntity>()
				.in(PostEntity::getId, postIds)
				.orderByDesc(PostEntity::getCreatedAt)
		);
		
		return ApiResponse.ok(posts);
	}
}

